# coding=utf-8
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from flask_restful import Resource, Api, reqparse, fields, marshal_with, abort, marshal
from models import db, User


app = Flask(__name__)
app.config.update(RESTFUL_JSON=dict(ensure_ascii=False))

# 设置连接数据库的URL
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:密码@ip:3306/health?charset=utf8'

# 设置每次请求结束后会自动提交数据库中的改动
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# 查询时会显示原始SQL语句
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)

errors = {
    'UserAlreadyExistsError': {
        'message': "A user with that username already exists.",
        'status': 409,
    },
    'ResourceDoesNotExist': {
        'message': "A resource with that ID no longer exists.",
        'status': 410,
        'extra': "Any extra information you want.",
    }
}

api = Api(app)

resource_full_fields = {
    'id': fields.Integer,
    'name': fields.String,
    'password': fields.String
}


class Hello(Resource):
    def get(self):
        dictionaries = {"name": "longtao", "age": 27}
        return dictionaries

    def post(self):
        dictionaries = {"name": "longtao", "age": 27}
        return dictionaries


class Common:
    def returnTrueJson(self, data, msg="请求成功"):
        return jsonify({
            "status": 1,
            "data": data,
            "msg": msg
        })

    def returnFalseJson(self, data=None, msg="请求失败"):
        return jsonify({
            "status": 0,
            "data": data,
            "msg": msg
        })


class Users(Resource):
    @staticmethod
    def post(userId):
        print(request.method)
        user = User.query.filter_by(id=userId).first();
        if user is None:
            abort(410, msg="找不到数据", data=None, status=0)
        else:
            return Common.returnTrueJson(Common, marshal(user, resource_full_fields))

    @staticmethod
    def get(userId):
        print(request.method)
        user = User.query.filter_by(id=userId).first();
        if user is None:
            abort(410, msg="找不到数据", data=None, status=0)
        else:
            return Common.returnTrueJson(Common, marshal(user, resource_full_fields))


@app.route('/')
def hello_world():
    # result = User.query.first()
    # print(result)
    return 'Hello World!'


api.add_resource(Hello, '/index')
api.add_resource(Users, '/users/<int:userId>')

'''
ModuleNotFoundError: No module named 'MySQLdb'
pip install mysqlclient
'''
if __name__ == '__main__':

    app.run(debug=True)
